package com.zhiche.lisa.integration.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.collect.Maps;
import com.zhiche.lisa.core.enums.IntegrationURIEnum;
import com.zhiche.lisa.core.enums.TableStatusEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.integration.dao.model.ExportLog;
import com.zhiche.lisa.integration.dao.model.ExportLogHistory;
import com.zhiche.lisa.integration.dao.model.ImportLogHistory;
import com.zhiche.lisa.integration.dao.model.PushSubSystem;
import com.zhiche.lisa.integration.dto.tms.TmsCommonDTO;
import com.zhiche.lisa.integration.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
public class TMSServiceImpl implements TMSAPIService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TMSServiceImpl.class);

    @Autowired
    private IImportLogService logService;
    @Autowired
    private IExportLogService exportLogService;
    @Autowired
    private IExportLogHistoryService exportLogHistoryService;
    @Autowired
    private IPushSubSystemService pushSubSystemService;

    @Override
    public void shipDeliver(TmsCommonDTO dto) {
        String paramJson = JSONObject.toJSONString(dto);
        LOGGER.info("integration 司机公众号接收到发运参数:{}", paramJson);
        HashMap<String, String> otmParams = Maps.newHashMap();
        otmParams.put("shipment_gid", "ULC/ZC." + dto.getShipmentGid());
        otmParams.put("key", dto.getShipPicKeys());
        otmParams.put("depart_time", dto.getDepartTime());
        String otmParam = JSONObject.toJSONString(otmParams);
        //导入日志
        ImportLogHistory importLogHistory = new ImportLogHistory();
        importLogHistory.setSourceSys("TMS");
        importLogHistory.setSourceKey(dto.getShipmentGid());
        importLogHistory.setType(IntegrationURIEnum.TMS_DELIVER.getCode());//205
        importLogHistory.setImportStartTime(new Date());
        importLogHistory.setImportEndTime(new Date());
        new Thread(() -> {
            LOGGER.info("开始保存导入日志---------------");
            try {
                logService.saveImportLogToQiniu(importLogHistory, otmParam);
            } catch (Exception e) {
                LOGGER.error("日志保存失败---------------");
            }
            LOGGER.info("完成日志保存---------------");
        }).start();
        Wrapper<PushSubSystem> ew = new EntityWrapper<>();
        ew.eq("type", IntegrationURIEnum.TMS_DELIVER.getCode());
        List<PushSubSystem> pushSubSystems = pushSubSystemService.selectList(ew);
        if (CollectionUtils.isNotEmpty(pushSubSystems)) {
            for (PushSubSystem subSystem : pushSubSystems) {
                String url = subSystem.getUrl();
                Integer socketTimeOut = subSystem.getSocketTimeOut();
                LOGGER.info("TMSAPIServiceImpl.shipDeliver(公众号发运) url:{},PARAM:{} result:{}", url, otmParam);
                String result = HttpClientUtil.postJson(url, null, otmParam, socketTimeOut);
                LOGGER.info("TMSAPIServiceImpl.shipDeliver(公众号发运) result:{}", result);
                if (StringUtils.isBlank(result)) {
                    throw new BaseException("OTM返回接口为空");
                } else {
                    JSONObject jsonObject = JSON.parseObject(result);
                    boolean success = jsonObject.getBoolean("success");
                    if (!success) {
                        throw new BaseException(jsonObject.getString("message"));
                    }
                }
            }
        }
    }


    @Override
    public void sendXMLShipToProv(TmsCommonDTO dto) {
        LOGGER.info("integration 无车承运人运抵推送省平台   key-->:{}", dto.getSourceKey());
        //导入日志
        String xml = dto.getXml();
        ExportLogHistory exportLogHistory = new ExportLogHistory();
        exportLogHistory.setTargertSys("tms-无车承运人");
        exportLogHistory.setExportKey(dto.getSourceKey());
        exportLogHistory.setType(IntegrationURIEnum.SHIP_TO_PROV.getCode());
        exportLogHistory.setExportStartTime(new Date());
        exportLogHistory.setExportEndTime(new Date());

        Wrapper<PushSubSystem> ew = new EntityWrapper<>();
        ew.eq("type", IntegrationURIEnum.SHIP_TO_PROV.getCode());
        List<PushSubSystem> pushSubSystems = pushSubSystemService.selectList(ew);
        if (CollectionUtils.isNotEmpty(pushSubSystems)) {
            exportLogHistory.setInterfaceUrl(pushSubSystems.get(0).getUrl());
            new Thread(() -> {
                LOGGER.info("开始保存导入日志---------------");
                try {
                    exportLogService.saveExportLogToQiniu(exportLogHistory, JSONObject.toJSONString(dto));
                } catch (Exception e) {
                    LOGGER.error("日志保存失败---------------");
                }
                LOGGER.info("完成日志保存---------------");
            }).start();
            for (PushSubSystem subSystem : pushSubSystems) {
                String url = subSystem.getUrl();
                try {
                    LOGGER.info("ErpShippingService.无车承运人运抵推送省平台 url:{}, xml:{} ", url, xml);
                    String result = postXml(xml, subSystem, url);
                    LOGGER.info("ErpShippingService.无车承运人运抵推送省平台 url:{},key:{} result:{}", url, dto.getSourceKey(), result);
                    if (StringUtils.isNotBlank(result)) {
                        String isSuccess = StringUtils.substringBetween(result, "<isSuccess>", "</isSuccess>");
                        EntityWrapper<ExportLogHistory> exportHistoryEW = new EntityWrapper<>();
                        exportHistoryEW.eq("export_key", dto.getSourceKey())
                                .eq("type", IntegrationURIEnum.SHIP_TO_PROV.getCode())
                                .eq("targert_sys", "tms-无车承运人");
                        EntityWrapper<ExportLog> exportEW = new EntityWrapper<>();
                        exportEW.eq("export_key", dto.getSourceKey())
                                .eq("type", IntegrationURIEnum.SHIP_TO_PROV.getCode())
                                .eq("targert_sys", "tms-无车承运人");
                        if (Boolean.valueOf(isSuccess)) {
                            ExportLogHistory nH = new ExportLogHistory();
                            nH.setExportStatus(TableStatusEnum.STATUS_TRUE.getCode());
                            exportLogHistoryService.update(nH, exportHistoryEW);
                            ExportLog el = new ExportLog();
                            el.setExportStatus(TableStatusEnum.STATUS_TRUE.getCode());
                            exportLogService.update(el, exportEW);
                        } else {
                            String reason = StringUtils.substringBetween(result, "<reason>", "</reason>");
                            ExportLogHistory nH = new ExportLogHistory();
                            nH.setExportStatus(TableStatusEnum.STATUS_FALSE.getCode());
                            nH.setExportRemarks(reason);
                            exportLogHistoryService.update(nH, exportHistoryEW);
                            ExportLog el = new ExportLog();
                            el.setExportStatus(TableStatusEnum.STATUS_FALSE.getCode());
                            el.setExportRemarks(reason);
                            exportLogService.update(el, exportEW);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("ErpShippingService.无车承运人运抵推送省平台 url:{} 连接超时--> error:{}", url, e);
                }
            }
        }
    }

    private String postXml(String xml, PushSubSystem subSystem, String url) {
        CloseableHttpClient client = HttpClients.createDefault();
        String result = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost method = new HttpPost(url);
            RequestConfig.Builder builder = RequestConfig.custom().setConnectTimeout(300000).setSocketTimeout(subSystem.getSocketTimeOut());
            method.setConfig(builder.build());
            StringEntity body = new StringEntity(xml, "UTF-8");
            body.setContentType(MediaType.APPLICATION_XML_VALUE);
            method.setEntity(body);
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (!Objects.isNull(response)) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
